﻿using Microsoft.AspNetCore.Mvc;
using PuppeteerSharp;
using SelectPdf;

namespace Dotnet6Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class PdfDownloadController : Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            //var chromeOptions = new ChromeOptions();
            //chromeOptions.AddArguments("--headless");
            ////"C:\\Users\\72769\\.nuget\\packages\\selenium.webdriver.chromedriver\\122.0.6261.6901\\driver\\win32\\chromedriver.exe"
            //var chromeDriver = new ChromeDriver(chromeOptions);

            //chromeDriver.Navigate().GoToUrl("https://www.baidu.com");

            //chromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(8);

            //var printOptions = new Dictionary<string, object>
            //{
            //    { "paperWidth", 210 / 25.4 },
            //    { "paperHeight", 297 / 25.4 },
            //    { "scale", 0.9 },
            //    { "pages", "all" }
            //};

            //var output = chromeDriver.ExecuteCustomDriverCommand("Page.printToPDF", printOptions) as Dictionary<string, object>;

            //var pdfStr = output["data"] as string ?? string.Empty;

            //var bytes = Convert.FromBase64String(pdfStr);

            //return File(bytes, "application/pdf");

            var converter = new HtmlToPdf
            {
                Options =
                {
                    // set converter options
                    PdfPageSize = PdfPageSize.A4,
                    PdfPageOrientation = PdfPageOrientation.Landscape,
                    WebPageWidth = 1024,
                    //WebPageHeight = 1080
                }
            };

            var doc = converter.ConvertUrl("file:///C:/Users/72769/Desktop/aaa.html");
            var ms = new MemoryStream();
            doc.Save(ms);
            doc.Close();
            var byteArray = ms.ToArray();
            ms.Dispose();

            return File(byteArray, "application/pdf");
        }

        [HttpGet("[action]")]
        public async Task<IActionResult> Index1()
        {
            //var fetcher = new BrowserFetcher();
            //await fetcher.DownloadAsync();
            await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, ExecutablePath = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" });
            var page = await browser.NewPageAsync();

            await page.GoToAsync("file:///C:/Users/72769/Desktop/aaa.html");
            var byteArray = await page.PdfDataAsync();

            return File(byteArray, "application/pdf");
        }
    }
}
